package com.lch.designpattern.proxy.dbroute.proxy;

import com.lch.designpattern.proxy.dbroute.db.DynamicDataSourceEntity;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: liuchenhui
 * @create: 2019-04-18 22:14
 **/
@SuppressWarnings("all")
public class OrderServiceDynamicProxy implements InvocationHandler {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");

    private Object proxyObject;

    public Object getInstance(Object proxyObject) {
        this.proxyObject = proxyObject;
        Class<?> clazz = proxyObject.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);
        Object object = method.invoke(proxyObject, args);
        after();
        return object;
    }

    private void after() {
        System.out.println("after");
        // 还原数据源
        DynamicDataSourceEntity.restore();
    }

    private void before(Object target) {
        try {
            System.out.println("before");
            Long time = (Long) target.getClass().getMethod("getCreateTime").invoke(target);
            Integer dbRoute = Integer.valueOf(dateFormat.format(new Date(time)));
            System.out.println("静态代理类自动分配到【DB_" + dbRoute + "】数据源动态切换");
            // 设置数据源
            DynamicDataSourceEntity.set(dbRoute);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }
}
